import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import xyz.chaobei.common.Student;

import java.io.*;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2021/1/8
 */
@Slf4j
public class TestOutputStream {

    @Test
    public void testObjectOutput() throws IOException {

        final String FILE_PATH = "D:\\obj.dat";

        Student student = new Student(1, "mrc", 18);

        OutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;

        try {
            File file = new File(FILE_PATH);

            if (!file.exists()) {
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file);
            objectOutputStream = new ObjectOutputStream(outputStream);

            objectOutputStream.writeObject(student);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (Objects.nonNull(objectOutputStream)) {
                objectOutputStream.close();
            }
            if (Objects.nonNull(outputStream)) {
                outputStream.close();
            }

        }
    }

    @Test
    public void testByteOutputStream() {
        final String FILE_PATH = "D:\\obj.dat";

        try (InputStream inputStream = new FileInputStream(FILE_PATH)) {

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            byte[] bytes = new byte[64];
            int num = 0;
            while ((num = inputStream.read(bytes)) != -1) {
                log.info("read num={}", num);
                outputStream.write(bytes, 0, num);
            }

            byte[] array = outputStream.toByteArray();
            log.info("read array length={}", array.length);
            log.info("read array={}", Arrays.toString(array));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
